<template>
  <a-modal
    :title="formTile + '图案'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <a-card>
      <a-row
        type="flex"
        justify="start"
        align="top"
      >
        <a-col :span="24">
          <a-form
            :form="form"
            @submit="handleSubmit"
            :labelCol="formItemLayout.labelCol"
            :wrapperCol="formItemLayout.wrapperCol"
          >
            <a-form-item
              label="名称"
              :required="true"
            >
              <a-input
                placeholder="请输入名称"
                :maxLength="40"
                allow-clear
                v-decorator="[
                  `name`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入名称'
                      }
                    ]
                  }
                ]"
              />
            </a-form-item>
            <a-form-item
              label="品牌"
              :required="true"
            >
              <a-select
                placeholder="请选择品牌"
                @change="selectChange"
                v-decorator="['brandCode',  {
                    rules: [{ required: true, message: '请选择品牌!' }],
                  },]"
                allow-clear
              >
                <a-select-option
                  :value="item.code"
                  v-for="(item, index) in brands"
                  :key="`${item.code}-${index}`"
                >
                  {{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="季节"
              :required="true"
            >
              <a-select
                allow-clear
                show-search
                placeholder="请选择季节"
                v-decorator="[
                  'season',
                  {
                    rules: [{ required: true, message: '请选择季节!' }]
                  }
                ]"
              >
                <a-select-option
                  :value="item.code"
                  v-for="item in seasons"
                  :key="item.code"
                >
                  {{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="是否有英文">
              <a-switch
                v-decorator="['whetherHasEnglish', { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择是否有英文' }] }]"
                @change="switchLang"
              ></a-switch>
            </a-form-item>
            <a-form-item
              label="英文原文"
              v-if="showEn"
            >
              <a-textarea
                allow-clear
                placeholder="请输入英文原文"
                v-decorator="['englishOriginal', { rules: [{ required: true, message: '请输入英文原文' }] }]"
              ></a-textarea>
            </a-form-item>
            <a-form-item
              label="英文解释"
              v-if="showEn"
            >
              <a-textarea
                allow-clear
                placeholder="请输入英文解释"
                v-decorator="['englishExplain', { rules: [{ required: true, message: '请输入英文解释' }] }]"
              ></a-textarea>
            </a-form-item>
            <a-form-item
              label="图案出处"
              allow-clear
            >
              <a-radio-group
                name="radioGroup"
                v-decorator="['source', { initialValue: 1, rules: [{ required: true, message: '请选择图案出处!' }] }]"
              >
                <a-radio :value="1"> 原创 </a-radio>
                <a-radio :value="2"> 借鉴 </a-radio>
                <a-radio :value="3"> 出处 </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="是否存在敏感风险">
              <a-switch
                v-decorator="[
                  'riskFlag',
                  { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择是否存在敏感风险！' }] },
                ]"
                @change="changeRisk"
              ></a-switch>
            </a-form-item>
            <a-form-item
              v-if="showRisk"
              label="敏感风险"
            >
              <a-checkbox-group v-decorator="['risk', {rules: [{ required: true, message: '请选择存在的敏感风险！' }]}]">
                <a-row>
                  <a-col
                    :span="20"
                    v-for="(item,index) in riskList"
                    :key="index"
                  >
                    <a-checkbox :value="item.value">
                      {{ item.title }}
                      <a-popover>
                        <template slot="content">
                          <p
                            v-for="(tip,index) in item.tips"
                            :key="index"
                          >
                            {{tip}}
                          </p>

                        </template>
                        <a-icon
                          type="question-circle"
                          theme="twoTone"
                          class="tips"
                        />
                      </a-popover>
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
            <a-form-item label="含义">
              <a-textarea
                allow-clear
                placeholder="请输入含义"
                v-decorator="['meaning', { rules: [{ required: true, message: '请输入含义' }] }]"
              ></a-textarea>
            </a-form-item>
            <a-form-item
              label="图片"
              :required="true"
            >
              <a-upload
                name="file"
                list-type="picture-card"
                :multiple="true"
                class="avatar-uploader"
                :data="{ type: 2,brand:brandName }"
                :action="uploadUrl"
                :fileList="fileList"
                :before-upload="beforeUpload"
                @change="handleChange"
                v-decorator="[
                  'url',
                  {
                    rules: [{ required: true, message: '请上传图片' }],
                  },
                ]"
              >
                <div v-if="fileList.length <= 5">
                  <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-row>
              <a-col
                :span="16"
                :offset="8"
                class="info-action"
              >
                <a-button
                  type="primary"
                  @click="reset"
                >返回</a-button>
                <a-button
                  type="primary"
                  class="ml-20"
                  html-type="submit"
                  :loading="loading"
                >保存</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </a-modal>
</template>

<script>
import { getSystemPro, currencyCreate, currencyUpdate, uploadUrl, queryDetail } from '@api/pattern/index.js'
import { pattern } from '@api/pattern/index'
import { postAction } from '@/api/manage'

const riskList = [
  {
    title: '原创／著作问题',
    value: '10',
    tips: [
      '1.包含其他作品(艺术品/画作等)或者其他品牌logo。例如：未经授权不可包含第三方作品及其他品牌logo',
      '2.包含一些个人隐私信息。例如：素材中不能包含个人信息、名字、手机、身份证、车牌等',
      '3.没有肖像授权。例如：素材中的模特需提前签订肖像授权',
      '4.包含一些无法提供证明的用词?“最”"第一等。例如：素材中不能出现无法提供报告证明的文字描述，违反广告法'
    ]
  },
  {
    title: '社会和谐',
    value: '20',
    tips: [
      '1.有恐怖、暴力倾向。例如：枪支，而腥、斗殴，愤怒等，暴力也包含冷暴力',
      '2.有色情或性暗示倾向。例如：过度裸震姿势暗示性元素及语言等',
      '3.有邪教图案。例如：佛像、撒旦元素、耶稣十字架、法轮功等',
      '4.有恋童倾向。例如：儿童做一些性暗示的动作，或者和此类元素互动'
    ]
  },
  {
    title: '政治敏感',
    value: '30',
    tips: [
      '1.包含了错误的地图及地域信息。例如：台湾问题及地图不完整，涉及国家主权问题',
      '2.提及人物是否有反华的言论。例如：D&G创始人在facebook的言论',
      '3.有辱华的元素。例如：东方人丑化=眯眯眼，三只松鼠海报事件',
      '4.包含一些历史事件元素。例如：历史革命的元素和标志，“平等”“主席像”“坦克”等',
      '5.发布时间，是否恰当。例如：918事变，77卢沟桥事变，1213南京大屠杀。512汶川地震等',
      '6.包含其他国家的国旗、军旗、侵略国的元素。例如：穿国旗事件，靖国神社前拍照'
    ]
  },
  {
    title: '文化歧视',
    value: '40',
    tips: [
      '1.影射种族歧视。例如：有色人群:黑人=猩猩，辱华:中国人=眯眯眼',
      '2.对女性的物化及不尊重。例如：存在对物化、过度定义不尊重',
      '3.少于50%是中国亚洲模特。例如：中国设计师品牌的立场',
      '4.对特殊人群的暗讽。例如：佛像，撒日元素，耶稣十字架，法轮功等'
    ]
  },
  {
    title: '语言问题',
    value: '50',
    tips: ['1.英文含义解读是否有风险。例如：welcometo hell，不能当作图案使用', '2.英文表示在西方文化中是否有双关含义。例如：Dog 直译是狗，但会有侮辱嫌疑，可以改用puppy']
  },
  {
    title: '未成年人风险',
    value: '60',
    tips: [
      '1.是否含有引发未成年人模仿违反社会公德的行为和违法犯罪的行为。',
      '2.是否含有恐怖、残酷等可能妨害未成年人身心健康的行为。',
      '3.是否含有可能引发未成年人模仿的不安全行为。',
      '4.是否可能引发未成年人产生不良情绪、养成不良嗜好。',
      '5.如素材涉及境外文化作品的，是否来源于国内审定引进版本'
    ]
  }
]
export default {
  props: {
    patternId: {
      type: [Number, String],
      default: ''
    }
  },

  data() {
    return {
      riskList,
      autoExpandParent: true,
      tip: '如未选择元素，系统将自动使用图案的第一个颜色图片作为元素关联图案',
      seasons: [],
      brands: [],
      current: 1,
      size: 1000,
      total: 0,
      linkName: '',
      loading: false,
      fileds: [],
      uploading: false,
      uploadLoading: false,

      treevalue: [],
      templates: [],
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 8 },
          xs: { span: 12 },
          sm: { span: 12 }
        }
      },
      fileList: [],
      imageUrl: '',
      dataId: '',
      colorid: '',
      brandName:'',
      images: [],
      dele: 0,
      uploadUrl,
      record: null,
      pushType: undefined,
      formTile: '新增',
      showEn: false,
      showRisk: false,
      pattern: null,
      value: undefined
    }
  },

  computed: {
    userInfo() {
      return this.$store.getters.userInfo || null
    },
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'category' })
  },

  created() {
    this.getsysPro()
    this.getBrandList()
    const { patternId } = this.$props
    if (patternId) {
      this.formTile = '编辑'
      this.getDetail(patternId)
    }
  },

  methods: {
    async getDetail(id) {
      try {
        const res = await queryDetail('pattern/fast', { id })
        if (res.code == 200) {
          this.currentEditionId = res.data.currentEditionId
          this.colorid = res.data.colorId
          this.$nextTick(() => {
            this.brandName = res.data.brandCode
            this.currentEditionId = res.data.currentEditionId
            this.form.setFieldsValue({
              name: res.data.name,
              brandCode: res.data.brandCode,
              season: res.data.season,
              elements: res.data.elements.map(item => {
                return item.id
              }),
              meaning: res.data.meaning,
              remarks: res.data.remarks,
              source: res.data.source,
              decorateAccessories: res.data.decorateAccessories == 1,
              whetherHasEnglish: res.data.whetherHasEnglish == 1,
              riskFlag: res.data.riskFlag == 1
            })
            if (res.data.whetherHasEnglish == 1) {
              this.showEn = true
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  englishExplain: res.data.englishExplain,
                  englishOriginal: res.data.englishOriginal
                })
              })
            }
            if (res.data.riskFlag == 1) {
              this.showRisk = true
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  risk: res.data.risk
                })
              })
            }
            const images = res.data.images
            if (Array.isArray(images) && images.length > 0) {
              this.fileList = images.map(item => {
                return {
                  name: item.name,
                  uid: item.url,
                  status: 'done',
                  url: item.url
                }
              })
              this.form.setFieldsValue({
                url: images.map(item => {
                  return {
                    name: item.name,
                    url: item.url
                  }
                })
              })
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      } catch (error) {
        this.$message.error(error.msg || '出错了')
      }
    },
     selectChange(brand){
      this.brandName = brand
    },
    handleChange(info) {
      let fileList = [...info.fileList]
      this.fileList = info.fileList
      if (info.file.status === 'uploading') {
        this.uploading = true
        return
      }
      if (info.file.status === 'done') {
        this.uploading = false
        let list = fileList.map(file => {
          if (file.response) {
            if (file.response.code == 200) {
              if (file.response.data.yidunSuggestion == 0) {
                file.dataId = file.response.data.dataId
              } else {
                let that = this
                that.$message.error(file.response.data.yidunExplain ? '该图案包含' + file.response.data.yidunExplain : '该图案包含敏感内容')
                file.status = 'error'
                // that.$confirm({
                //   content: file.response.data.yidunExplain ? '该图案包含' + file.response.data.yidunExplain + '要继续上传吗？' : '该图案包含敏感内容，要继续上传吗？',
                //   onOk: () => {
                //     file.dataId = file.response.data.dataId
                //   },
                //   onCancel() {
                //     that.fileList.pop()
                //   }
                // })
              }
              file.url = file.response.data.url
            } else {
              this.$message.error('图片上传失败')
              this.fileList.pop()
              return fileList
            }
          }
          return file
        })
        this.fileList = list.filter(file => file.status != 'error');
      }
      if (info.file.status === 'error') {
        this.$message.error('图片上传失败')
      }
    },

    beforeUpload: function (file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    async getBrandList() {
      const data = {
        jobNumber: this.jobNumber
      }
      const res = await getSystemPro('brand', data)
      if (res.code == 200) {
        this.brands = res.data
        this.brands = this.brands.sort((a, b) => {
          const arr = ['JNBY', '速写', 'LESS', 'jnby by JNBY', 'jnby for mini', 'Pomme de terre', 'A PERSONAL NOTE 73', 'JNBY HOME']
          return arr.indexOf(a.code) - arr.indexOf(b.code)
        })
      } else {
        this.$message.error(res.msg || res.message)
      }
    },
    async getsysPro() {
      try {
        const res = await getSystemPro('season') //queryFull('element')
        this.seasons = res.data || []
        this.seasons = this.seasons.sort((a, b) => {
          return b.code.localeCompare(a.code, 'zh-CN')
        })
      } catch (error) {
        console.log(error)
      }
    },
    switchLang(status) {
      this.showEn = status
    },
    changeRisk(status) {
      this.showRisk = status
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.setFieldsValue({
        url: this.fileList.map(item => {
          return {
            name: item.name,
                                       dataId: item.dataId ? item.dataId : '',

            url: item.url
          }
        })
      })
      this.form.validateFields((err, values) => {
        console.log(err, values)
        if (!err) {
          this.submit(values)
        }
      })
    },
    async submit(values) {
      console.log(values.url)
      this.loading = true
      const { workNo, realname } = this.userInfo
      const { patternId } = this
      if (patternId) {
        values.id = this.patternId
      }
      values.decorateAccessories = values.decorateAccessories ? 1 : 0
      values.whetherHasEnglish = values.whetherHasEnglish ? 1 : 0
      values.riskFlag = values.riskFlag ? 1 : 0
      values.designerUserId = workNo
      values.designerUserName = realname
      values.jobNumber = workNo
      try {
        const urls = values.url || []
        const images = urls.map(item => {
          return {
            name: item.name,
            dataId: item.dataId ? item.dataId : '',
            url: item.url ? item.url : item.response.data.url
          }
        })
        const imageList = urls.map(item => {
          return item.url ? item.url : item.response.data.url
        })
        values.images = images
        values.url = ''
        if (patternId) {
          values.editionId = this.currentEditionId
          const checkParams = {
            colorId: this.colorid,
            imageList: imageList,
            patternId: this.patternId,
            scene: 1
          }
          postAction(`${pattern}pattern/examine/check`, checkParams).then(res => {
            if (res.code != 200) {
              this.$confirm({
                content: res.msg,
                onOk: () => {
                  postAction(`${pattern}pattern/fast/update`, values).then(res => {
                    if (res.code == 200) {
                      this.$message.success('编辑成功')
                      let operate = 1
                      this.reset(values, operate)
                      this.loading = false
                    } else {
                      this.$message.error(res.msg || res.message)
                      this.loading = false
                    }
                  })
                  const initParams = {
                    colorId: this.colorid,
                    patternId: this.patternId,
                    scene: 1,
                    jobNumber: this.jobNumber
                  }
                  postAction(`${pattern}pattern/examine/init`, initParams).then(res => {
                    if ((res.data = 200)) {
                      this.$message.success('图案审核/批注状态已重置')
                    }
                  })
                },
                onCancel: () => {
                  this.reset()
                }
              })
            } else {
              postAction(`${pattern}pattern/fast/update`, values).then(res => {
                if (res.code == 200) {
                  this.$message.success('编辑成功')
                  let operate = 1
                  this.reset(values, operate)
                  this.loading = false
                } else {
                  this.$message.error(res.msg || res.message)
                  this.loading = false
                }
              })
            }
          })
        } else {
          postAction(`${pattern}pattern/fast/save`, values).then(res => {
            if (res.code == 200) {
              this.$message.success('新建成功')
              let operate = 0
              this.reset(values, operate)
              this.loading = false
            } else {
              this.$message.error(res.msg || res.message)
              this.loading = false
            }
          })
        }
      } catch (error) {
        this.loading = false
      }
    },
    reset(values, operate) {
      this.form.resetFields()
      this.loading = false
      this.fileList = []
      this.fileds = []
      this.$emit('close', values, operate)
      // this.$emit("changeEvent", values,operate);
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}
.ml-20 {
  margin-left: 20px;
}
.poster {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  position: relative;
  &:hover {
    .img-modal {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .img {
    width: 100%;
    height: 100%;
  }
  .img-modal {
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    position: absolute;
    color: #fff;
    font-size: 20px;
    width: 100%;
    top: 0;
    height: 100%;
    left: 0;
  }
}
.fileList {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}
.tips {
  margin-left: 5px;
  cursor: pointer;
}
</style>
